{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Preamble to mimick book environment\n",
    "import logging\n",
    "from pprint import pprint\n",
    "from sys import stdout as STDOUT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bucket(quota=0)\n"
     ]
    }
   ],
   "source": [
    "# Example 1\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "class Bucket(object):\n",
    "    def __init__(self, period):\n",
    "        self.period_delta = timedelta(seconds=period)\n",
    "        self.reset_time = datetime.now()\n",
    "        self.quota = 0\n",
    "\n",
    "    def __repr__(self):\n",
    "        return 'Bucket(quota=%d)' % self.quota\n",
    "\n",
    "bucket = Bucket(60)\n",
    "print(bucket)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 2\n",
    "def fill(bucket, amount):\n",
    "    now = datetime.now()\n",
    "    if now - bucket.reset_time > bucket.period_delta:\n",
    "        bucket.quota = 0\n",
    "        bucket.reset_time = now\n",
    "    bucket.quota += amount"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 3\n",
    "def deduct(bucket, amount):\n",
    "    now = datetime.now()\n",
    "    if now - bucket.reset_time > bucket.period_delta:\n",
    "        return False\n",
    "    if bucket.quota - amount < 0:\n",
    "        return False\n",
    "    bucket.quota -= amount\n",
    "    return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bucket(quota=100)\n"
     ]
    }
   ],
   "source": [
    "# Example 4\n",
    "bucket = Bucket(60)\n",
    "fill(bucket, 100)\n",
    "print(bucket)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Had 99 quota\n",
      "Bucket(quota=1)\n"
     ]
    }
   ],
   "source": [
    "# Example 5\n",
    "if deduct(bucket, 99):\n",
    "    print('Had 99 quota')\n",
    "else:\n",
    "    print('Not enough for 99 quota')\n",
    "print(bucket)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Not enough for 3 quota\n",
      "Bucket(quota=1)\n"
     ]
    }
   ],
   "source": [
    "# Example 6\n",
    "if deduct(bucket, 3):\n",
    "    print('Had 3 quota')\n",
    "else:\n",
    "    print('Not enough for 3 quota')\n",
    "print(bucket)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Example 7\n",
    "class Bucket(object):\n",
    "    def __init__(self, period):\n",
    "        self.period_delta = timedelta(seconds=period)\n",
    "        self.reset_time = datetime.now()\n",
    "        self.max_quota = 0\n",
    "        self.quota_consumed = 0\n",
    "\n",
    "    def __repr__(self):\n",
    "        return ('Bucket(max_quota=%d, quota_consumed=%d)' %\n",
    "                (self.max_quota, self.quota_consumed))\n",
    "\n",
    "# Example 8\n",
    "    @property\n",
    "    def quota(self):\n",
    "        return self.max_quota - self.quota_consumed\n",
    "\n",
    "# Example 9\n",
    "    @quota.setter\n",
    "    def quota(self, amount):\n",
    "        delta = self.max_quota - amount\n",
    "        if amount == 0:\n",
    "            # Quota being reset for a new period\n",
    "            self.quota_consumed = 0\n",
    "            self.max_quota = 0\n",
    "        elif delta < 0:\n",
    "            # Quota being filled for the new period\n",
    "            assert self.quota_consumed == 0\n",
    "            self.max_quota = amount\n",
    "        else:\n",
    "            # Quota being consumed during the period\n",
    "            assert self.max_quota >= self.quota_consumed\n",
    "            self.quota_consumed += delta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial Bucket(max_quota=0, quota_consumed=0)\n",
      "Filled Bucket(max_quota=100, quota_consumed=0)\n",
      "Had 99 quota\n",
      "Now Bucket(max_quota=100, quota_consumed=99)\n",
      "Not enough for 3 quota\n",
      "Still Bucket(max_quota=100, quota_consumed=99)\n"
     ]
    }
   ],
   "source": [
    "# Example 10\n",
    "bucket = Bucket(60)\n",
    "print('Initial', bucket)\n",
    "fill(bucket, 100)\n",
    "print('Filled', bucket)\n",
    "\n",
    "if deduct(bucket, 99):\n",
    "    print('Had 99 quota')\n",
    "else:\n",
    "    print('Not enough for 99 quota')\n",
    "\n",
    "print('Now', bucket)\n",
    "\n",
    "if deduct(bucket, 3):\n",
    "    print('Had 3 quota')\n",
    "else:\n",
    "    print('Not enough for 3 quota')\n",
    "\n",
    "print('Still', bucket)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
